#ifndef BASEPORT_H
#define BASEPORT_H

#include <QObject>
#include <QMutex>
#include <QTimer>
#include "portdefine.h"
#include "basefindpacket.h"
#include "portstatistics.h"
#include "basefindpacket.h"

class BasePort : public QObject
{
    Q_OBJECT

public:
    enum PortType
    {
        PortType_Unknown = 0,
        PortType_Serial,
    };

    BasePort(QObject *parent = nullptr);
    virtual ~BasePort();

    virtual PortType getPortType() = 0;

    void setName(QString name);
    QString &getName();

    void setID(PortID id);
    PortID getID() const;

    void setMagic(uint magic);
    uint getMagic();

    void setFinder(BaseFindPacket *finder);

    virtual void setConfig(QVariant &config) = 0;
    virtual QVariant getConfig(void) = 0;

    virtual bool open(void) = 0;
    virtual bool isOpen(void) = 0;
    virtual bool close(void) = 0;
    virtual qint32 write(const QByteArray &ba) = 0;
    virtual qint32 read(QByteArray &ba) = 0;

    virtual bool waitForFinished(int timeout_ms = -1);

    void start(void);

    PortStatistics *getPortStatistics() const;

public slots:
    void onSend(const QByteArray &ba);
    void on1sTimeout();

signals:
    void readCompleted(QByteArray ba);
    void receivePackets(QList<ProtocolPacket> packets);

protected:
    QMutex				*m_mutex = nullptr;
    QTimer				*m_timer = nullptr;
    PortStatistics      *m_statistics = nullptr;
    PortID              m_id = PortID_Unknown;
    QString             m_name;
    uint                m_magic;
    BaseFindPacket		*m_finder = nullptr;

    bool                m_syncFlag = true; // 专门用于跨线程同步用
};

#endif // BASEPORT_H
